import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

import { getToken, removeAll } from './auth'
// create an axios instance
import { AccessUrl } from '../consts'

export let baseUrl = process.env.VUE_APP_BASE_API || '/api'

if (process.env.VUE_APP_PROXY_API_FREFIX) {
  baseUrl = `${process.env.VUE_APP_PROXY_API_FREFIX}/api`
}



const service = axios.create({
  baseURL: baseUrl, // 暂时使用的测试地址
  timeout: 10000, // request timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF8',
    Accept: 'application/json',
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      // config.headers['X-Token'] = getToken()
      // config.headers['Authorization'] = getToken()
      config.headers.token = token
    }

    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  },
)
// response interceptor
service.interceptors.response.use(
  response => {
    // 非json数据
    if (response.headers['content-type'] && response.headers['content-type'] !== 'application/json') {
      return response
    }
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 401 || res.code === 403 || res.code === 404) {
        // to re-login
        MessageBox.confirm('登录信息已过期，请重新登录！', {
          confirmButtonText: '重新登录',
          showClose: false,
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          type: 'warning',
        }).then(() => {
          removeAll()
          window.location.replace(AccessUrl.indexUrl)
        })
        return
      }

      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000,
      })

      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  },
)




export default service
